using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using OneAuthCenter.Application.Services;
using OneAuthCenter.Application.Services.Implementations;
using OneAuthCenter.Domain.Repositories;
using OneAuthCenter.Infrastructure.Data;
using OneAuthCenter.Infrastructure.Repositories;
using OneAuthCenter.Infrastructure.Services;
using OneAuthCenter.Infrastructure.Extensions;
using OneAuthCenter.API.Middleware;

var builder = WebApplication.CreateBuilder(args);

// 添加服务到容器
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();

// 配置 Swagger（从配置文件读取）
var swaggerSettings = builder.Configuration.GetSection("SwaggerSettings");
if (swaggerSettings.GetValue<bool>("Enabled", true))
{
    builder.Services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo
        {
            Title = swaggerSettings["Title"] ?? "OneAuthCenter API",
            Version = swaggerSettings["Version"] ?? "v1",
            Description = swaggerSettings["Description"] ?? "OAuth 2.0 / OpenID Connect 认证中心",
            Contact = new OpenApiContact
            {
                Name = swaggerSettings["ContactName"] ?? "OneAuthCenter",
                Email = swaggerSettings["ContactEmail"] ?? "support@oneauthcenter.com"
            }
        });

        c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
        {
            Description = "JWT 授权头使用 Bearer 方案。示例: \"Authorization: Bearer {token}\"",
            Name = "Authorization",
            In = ParameterLocation.Header,
            Type = SecuritySchemeType.ApiKey,
            Scheme = "Bearer"
        });

        c.AddSecurityRequirement(new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                    }
                },
                Array.Empty<string>()
            }
        });
    });
}

// 使用配置化的数据库注入
builder.Services.AddConfiguredDatabase(builder.Configuration);

// 注册签名凭证服务（类似 IdentityServer 的 AddDeveloperSigningCredential）
var jwtSettings = builder.Configuration.GetSection("JwtSettings");
var useTestCert = jwtSettings.GetValue<bool>("SigningCertificate:UseTestCertificate");
var certPath = jwtSettings["SigningCertificate:CertificatePath"];
var certPassword = jwtSettings["SigningCertificate:CertificatePassword"];

var signingCredentialsService = new SigningCredentialsService(useTestCert, certPath, certPassword);
builder.Services.AddSingleton(signingCredentialsService);

// 配置 JWT 认证（使用 RSA 公钥验证）
// 注意：Issuer 和 Audience 在运行时动态获取（类似 IdentityServer4）
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.RequireHttpsMetadata = false; // 开发环境可以设为 false
    options.SaveToken = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = signingCredentialsService.GetValidationKey(), // 使用 RSA 公钥
        ValidateIssuer = false, // 动态 Issuer，在 Token 生成时设置
        ValidateAudience = false, // 动态 Audience，在 Token 生成时设置
        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero
    };
});

builder.Services.AddAuthorization();

// 注册仓储
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IClientRepository, ClientRepository>();
builder.Services.AddScoped<IRefreshTokenRepository, RefreshTokenRepository>();
builder.Services.AddScoped<IAuthorizationCodeRepository, AuthorizationCodeRepository>();
builder.Services.AddScoped<IScopeRepository, ScopeRepository>();
builder.Services.AddScoped<IUserConsentRepository, UserConsentRepository>();
builder.Services.AddScoped<IRevokedTokenRepository, RevokedTokenRepository>();

// 注册服务
builder.Services.AddScoped<ITokenService, TokenService>();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IOAuthService, OAuthService>();
builder.Services.AddScoped<IClientService, ClientService>();
builder.Services.AddScoped<IUserService, UserService>();

// 配置 CORS（配置化）
var corsSettings = builder.Configuration.GetSection("CorsSettings");
var allowAll = corsSettings.GetValue<bool>("AllowAll");
var allowedOrigins = corsSettings.GetSection("AllowedOrigins").Get<string[]>() ?? Array.Empty<string>();
var allowCredentials = corsSettings.GetValue<bool>("AllowCredentials");

builder.Services.AddCors(options =>
{
    options.AddPolicy("ConfiguredCorsPolicy", policy =>
    {
        if (allowAll)
        {
            // 允许所有来源（开发环境）
            policy.AllowAnyOrigin()
                  .AllowAnyMethod()
                  .AllowAnyHeader();
            Console.WriteLine("✓ CORS: 允许所有来源访问（AllowAll 模式）");
        }
        else
        {
            // 指定允许的来源（生产环境）
            policy.WithOrigins(allowedOrigins)
                  .AllowAnyMethod()
                  .AllowAnyHeader();
            
            if (allowCredentials)
            {
                policy.AllowCredentials();
            }
            
            Console.WriteLine($"✓ CORS: 允许指定来源访问 ({string.Join(", ", allowedOrigins)})");
        }
    });
});

// 添加 HttpContextAccessor（用于在服务中访问 HTTP 上下文）
builder.Services.AddHttpContextAccessor();

var app = builder.Build();

// 配置 HTTP 请求管道
// Swagger 根据配置文件启用/禁用（不依赖环境变量）
if (swaggerSettings.GetValue<bool>("Enabled", true))
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        var title = swaggerSettings["Title"] ?? "OneAuthCenter API";
        var version = swaggerSettings["Version"] ?? "V1";
        c.SwaggerEndpoint("/swagger/v1/swagger.json", $"{title} {version}");
        c.RoutePrefix = string.Empty; // 将 Swagger UI 设置为根路径
    });
    
    Console.WriteLine($"✓ Swagger UI: 已启用 ({app.Configuration["SwaggerSettings:Title"]})");
}
else
{
    Console.WriteLine("✗ Swagger UI: 已禁用（生产环境）");
}

// 显示当前数据库配置信息
var dbType = app.Configuration.GetConfiguredDatabaseType();
app.Logger.LogInformation("========================================");
app.Logger.LogInformation("OneAuthCenter 认证中心已启动");
app.Logger.LogInformation("当前使用数据库: {DatabaseType}", dbType);
app.Logger.LogInformation("========================================");

app.UseCors("ConfiguredCorsPolicy");
app.UseAuthentication();

// 使用 Token 黑名单验证中间件（必须在 UseAuthentication 之后）
app.UseMiddleware<TokenBlacklistMiddleware>();

app.UseAuthorization();
app.MapControllers();

app.Run();
